//
// FX Effect file - QUAD
//

matrix WorldVP:WorldViewProjection;

texture screenTX <
      	string Name = " ";
      >;	

sampler2D screen = sampler_state 
{
	Texture = <screenTX>;
	AddressU = Clamp; AddressV = Clamp;
	MinFilter = Linear; MagFilter = Linear; MipFilter = None;
};

float2 Scale = { 1, 1 };
float2 Size = { 640, 480 };
float4 DistortionX = { 0.0, 0.0, 0.0, 0.0 };
float4 DistortionY = { 0.0, 0.0, 0.0, 0.0 };
float4 DistortionRadius = { 0.0, 0.0, 0.0, 0.0 };
float4 DistortionStrength = { 0.0, 0.0, 0.0, 0.0 };

static const float PI = 3.14159265f;
static const float2 GameSize = { 1600, 1024 };
static const float invPI = 1.0/PI;
static const float2 invGameSize = 1.0/GameSize;

struct output
{
	float4 opos    : POSITION;  
 	float2 uv      : TEXCOORD0;  
};

output VS( float4 pos : POSITION )
{
	output OUT;
	OUT.uv = pos.xy * float2(0.5,-0.5) + 0.5;

	// Go here for more info: http://www.sjbrown.co.uk/?article=directx_texels
	float4 oPos = float4( pos.xy*Scale + float2( -1.0f/Size.x, 1.0f/Size.y ), 0.0, 1.0 );
	OUT.opos = oPos;

	return OUT;
}

float4 PS(output IN) : COLOR
{
	float2 uv = IN.uv*GameSize;
	float2 offset0 = float2 (DistortionX.x, DistortionY.x) - uv;
	float2 offset1 = float2 (DistortionX.y, DistortionY.y) - uv;
	float2 offset2 = float2 (DistortionX.z, DistortionY.z) - uv;
	float2 offset3 = float2 (DistortionX.w, DistortionY.w) - uv;
	float4 dist = float4 (length(offset0), length(offset1), length(offset2), length(offset3));
	float4 scale = (DistortionRadius*DistortionStrength*sin(dist*PI/DistortionRadius)/dist)*invPI;
	
	if (dist.x < DistortionRadius.x)
		uv += offset0*scale.x;
	if (dist.y < DistortionRadius.y)
		uv += offset1*scale.y;
	if (dist.z < DistortionRadius.z)
		uv += offset2*scale.z;
	if (dist.w < DistortionRadius.w)
		uv += offset3*scale.w;
	
	return tex2D(screen, uv*invGameSize);
}
  
technique screenquad
{
	pass p0
	{		
		VertexShader = compile vs_1_1 VS();
		PixelShader  = compile ps_2_0 PS();	
	}
}

